package cqut.wys.utils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

/**
 * Created by wuyoushan on 2017/11/20.
 */
public abstract class FileUtils {

    public static final String picDir="F://imgs";

    /**
     * 创建文件夹
     *
     * @param dir 路径
     */
    public  static void makeDir(String dir){
        File file = new File(dir);
        if (!file.exists()){
            file.mkdir();
        }
    }

    /**
     * 获取输入流
     *
     * @param src 图片url
     * @return InputStream
     */
    public static InputStream getInputStream(String src){
        //新建URL
        URL url = null;
        try {
            url = new URL(src);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }

        //新建URL连接类
        URLConnection urlConnection = null;
        //获取数据流
        InputStream inputStream = null;
        try {
            urlConnection = url.openConnection();
            inputStream = urlConnection.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return inputStream;
    }

    /**
     * 下载图片
     *
     * @param inputStream 文件流
     * @param fileName 文件名
     * @param dir 路径
     */
    public static void downloadPic(InputStream inputStream,String fileName,String dir){
        //需要判断inputStream是否为空，如果图片URL为404时候，不判空为导致程序中止
        if (inputStream != null){
            //写入数据
            OutputStream outputStream = null;
            try {
                File file = new File(dir,fileName);
                if (file.exists()){
                    return;
                }
                outputStream = new FileOutputStream(file);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            //下载图片
            byte[] buf = new byte[1024];
            int i;
            try {
                while ((i=inputStream.read(buf))!=-1){
                    outputStream.write(buf,0,i);
                    outputStream.flush();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                //下载完成就关闭文件流
                if (outputStream!=null){
                    try {
                        outputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    /**
     * 验证文件是否存在
     *
     * @param fileName 文件名
     * @param dir 文件路径
     * @return boolean
     */
    private static boolean isExistsFile(String fileName,String dir){
        File file = new File(dir,fileName);
        if (file.exists()){
            return true;
        }
        return false;
    }
}
